using System;
using System.Linq;
using System.Web.Mvc;
using SubSystem.Models;
using SubSystem.Models.ObjectStore;

namespace SubSystem.Controllers
{
    
    public class ArticleController : Controller
    {
        public ArticleController(ObjectManager<IArticle> objectManager)
        {
            Manager = objectManager;
        }

        public ObjectManager<IArticle> Manager { get; set; }

        public ActionResult Index()
        {
            return View(new ArticleModel(Manager));
        }

        [Authorize]
        public ViewResult Edit(Guid id)
        {
            var model = new ArticleModel(Manager);
            model.Article = model.Articles.Where(a => a.Id == id).FirstOrDefault();
            return View(model);
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Edit(Article article)
        {
            if (article.Content.Length < 25)
            {
                ModelState.AddModelError("ContentLength", "Article must be longer than 25 characters");
            }
            
            if (ModelState.IsValid)
            {
                if (Manager.Save(article))
                {
                    return RedirectToAction("Index");
                    // return View("Index", new ArticleModel(Manager));
                }

                ModelState.AddModelError("SaveFail", "Failed to save article.");
            }

            var model = new ArticleModel(Manager) {Article = article};
            return View(model); 
        }

        [Authorize]
        public ViewResult Add(Guid id)
        {
            var articleModel = new ArticleModel(Manager) {Article = new Article {Id = id}};
            return View("Edit", articleModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        [ValidateInput(false)]
        public ActionResult Add(Article article)
        {
            return Edit(article);
        }
    }
}
